package com.example.recorder;

import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.Toast;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;

/**
 * @author hdz
 * @date 2019/06/23
 */
public class MainActivity extends AppCompatActivity implements IWorkStateCallback {

    private Menu mMenu;
    private MenuItem mMenuItem;
    private FragmentManager mFragmentManager;
    private HomeFragment mHomeFragment;
    private WorkFragment mWorkFragment;
    private MyHandler mMyHandler;
    private boolean mIsSaveRecord = true;

    public WorkFragment getWorkFragment() {
        return mWorkFragment;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        initActionBar();

        mMyHandler = new MyHandler(this);

        mHomeFragment = new HomeFragment();
        mHomeFragment.setCallback(this);
        mHomeFragment.setHandler(mMyHandler);

        mFragmentManager = getSupportFragmentManager();
        FragmentTransaction fragmentTransaction = mFragmentManager.beginTransaction();
        fragmentTransaction.add(R.id.main_layout, mHomeFragment);
        fragmentTransaction.commit();

        requestPermission();
    }

    private void initActionBar() {
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.setDisplayHomeAsUpEnabled(true);
            actionBar.setHomeButtonEnabled(true);
        }
    }

    @Override
    public void onBackPressed() {
        moveTaskToBack(true);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.main, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.requestPermission:
                requestPermission();
                return true;
            case android.R.id.home:
                onBackPressed();
                return true;
            case R.id.stop:
                onAudioStop();
                return true;
            case R.id.cbSaveRecord:
                if (mIsSaveRecord) {
                    mIsSaveRecord = false;
                    mMenu.setGroupCheckable(R.id.group, false, false);
                } else {
                    mIsSaveRecord = true;
                    mMenu.setGroupCheckable(R.id.group, true, false);
                }
                mHomeFragment.setSaveRecord(mIsSaveRecord);
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        if (menu.size() >= 1) {
            mMenuItem = menu.getItem(0);
            mMenuItem.setVisible(false);
            mMenu = menu;
        }
        return super.onPrepareOptionsMenu(menu);
    }

    @Override
    public void onAudioStop() {
        if (mMenuItem != null) {
            mMenuItem.setVisible(false);
        }
        mHomeFragment.audioStop();
        FragmentTransaction fragmentTransaction = mFragmentManager.beginTransaction();
        fragmentTransaction.hide(mWorkFragment);
        fragmentTransaction.commit();
    }

    @Override
    public void onAudioPlay() {
        showWorkFragment();
    }

    @Override
    public void onAudioRecord() {
        showWorkFragment();
    }

    public void showWorkFragment() {
        FragmentTransaction fragmentTransaction = mFragmentManager.beginTransaction();
        if (mWorkFragment == null) {
            mWorkFragment = new WorkFragment();
            fragmentTransaction.add(R.id.main_layout, mWorkFragment);
        } else {
            fragmentTransaction.show(mWorkFragment);
        }
        fragmentTransaction.commit();
        if (mMenuItem != null) {
            mMenuItem.setVisible(true);
        }
    }

    private void requestPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            List<String> permissionList = new ArrayList<>();
            if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                permissionList.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
            }
            if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED) {
                permissionList.add(Manifest.permission.RECORD_AUDIO);
            }
            if (permissionList.size() > 0) {
                String[] permissions = permissionList.toArray(new String[0]);
                ActivityCompat.requestPermissions(this, permissions, 100);
            }
        }
    }

    private static class MyHandler extends Handler {
        private WeakReference<MainActivity> mMainActivityWeak;

        public MyHandler(MainActivity mainActivity) {
            mMainActivityWeak = new WeakReference<>(mainActivity);
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    mMainActivityWeak.get().onAudioStop();
                    break;
                case 1001:
                case 1002:
                    int err = msg.what - 1000;
                    if (err == 1) {
                        Toast.makeText(mMainActivityWeak.get(), "UNINITIALIZED", Toast.LENGTH_SHORT).show();
                    } else if (err == 2) {
                        Toast.makeText(mMainActivityWeak.get(), "STOPPED", Toast.LENGTH_SHORT).show();
                    }
                    break;
                default:
                    break;
            }
        }
    }
}
